<?php
require_once 'common.php';

/**
 * Kay-Value模型
 * @author wangjiajun
 *
 */
class OaKeyValueModel extends OpModel
{
    private $_keyValueTable;
    
    public static function getConstantValueByName($name, $default = 0)
    {
        return self::_getConstByName($name, '', $default, 'OaKeyValueModel');
    }
    
    public function __construct($logger = null)
    {
        if (is_null($logger)) {
            $logger = getOaModelLogger();
        }
        parent::__construct($logger);
        $dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
        $db = OpDbModel::getInstance($dbConfig, $logger);
        $this->_keyValueTable = new OpTableModel($db, 'key_value', $logger);
    }
    
    /**
     * 插入Key-Value对
     * @param string $key
     * @param string $value
     * @return boolean
     */
    public function add($key, $value)
    {
        return $this->_keyValueTable->insert(array(
            'k' => $key,
            'v' => $value
        ), null, false);
    }
    
    /**
     * 根据Key查询Value
     * @param string $key
     * @return string|null|boolean
     */
    public function get($key)
    {
        $row = $this->_keyValueTable->getRow(array(
            'k' => $key
        ));
        if ($row === false) {
            $this->_logger->log("get row failed");
            return false;
        }
        if (is_array($row)) {
            return $row['v'];
        } else {
            return null;
        }
    }
    
    /**
     * 修改Value
     * @param string $key
     * @param string $value
     * @return boolean
     */
    public function modify($key, $value)
    {
        return $this->_keyValueTable->update(array(
            'k' => $key
        ), array(
            'v' => $value
        ));
    }
    
    /**
     * 删除Key
     * @param string $key
     * @return boolean
     */
    public function delete($key)
    {
        return $this->_keyValueTable->delete(array(
            'k' => $key
        ));
    }
}